package com.example.security.component;

import com.example.security.service.TokenManager;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @application:
 * @author: LiYuhang
 * @Date: 2021/5/29 21:28
 * @version: 0.1
 * @Description :
 * @Modified By:
 */
@Component
public class JwtTokenManager implements TokenManager {
    
    private static final Logger log = LoggerFactory.getLogger(JwtTokenManager.class);
    
    @Value("${token.expire}")
    private long tokenExpiration = 3600;
    @Value("${token.key}")
    private String tokenSignKey;

    @Override
    public String createToken(String username) {
        String token = Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    @Override
    public String getUserFromToken(String token) {
        Claims body = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
        log.info("body:{}",body);
        String user = body.getSubject();
        return user;
    }

}
